package com.android.delivery.activity.fragment

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.android.delivery.adapter.PrintBlueAdapter
import com.android.delivery.base.BaseListFragmet
import com.android.delivery.constant.Constants
import com.android.delivery.entity.Logistics
import com.android.delivery.entity.print.BluetoothInfoBean
import com.android.delivery.util.GsonUtil
import com.android.delivery.util.print.service.Global
import com.android.delivery.util.print.service.ZPrinterManager
import com.blankj.utilcode.util.SPUtils
import com.tbruyelle.rxpermissions3.RxPermissions
import kotlinx.android.synthetic.main.include_refresh_layout.*
import java.util.*

/**
 * 打印机-蓝牙打印机列表
 */
open class PrintlnBlueListFragment : BaseListFragmet<BluetoothInfoBean>() {

    private var broadcastReceiver: BroadcastReceiver? = null
    private var intentFilter: IntentFilter? = null
    private var mHandler: MHandler? = null
    private val mInfoBeanList: ArrayList<BluetoothInfoBean> = ArrayList()
    private var mLogistics: Logistics? = null
    private var mRxPermissions: RxPermissions? = null

    private val printlnAdapter: PrintBlueAdapter by lazy {
        PrintBlueAdapter()
    }

    companion object {
        const val BT_STA_DISCONNECT = 0
        const val BT_STA_CONNECTING = 1
        const val BT_STA_CONNECTED = 2
        fun newInstance(logistics: Logistics): PrintlnBlueListFragment {
            val fragment = PrintlnBlueListFragment()
            val bundle = Bundle()
            if (logistics != null) {
                bundle.putParcelable(Constants.ITEM, logistics)
            }
            fragment.arguments = bundle
            return fragment
        }

        fun newInstance(): PrintlnBlueListFragment {
            val fragment = PrintlnBlueListFragment()
            return fragment
        }
    }

    override fun initData() {
        super.initData()
        mLogistics = arguments?.getParcelable(Constants.ITEM)
        mHandler = MHandler()
        initBroadcast()
        autoRefresh()

        //mPermissionCenter.permissionCheck(new String[]{Manifest.permission.WRITE_DATABASE});
    }

    override fun getEnableLoadMore(): Boolean {
        return false
    }

    override fun getEnableAutoRefresh(): Boolean {
        return false
    }

    override fun bindRecyclerView(recLv: RecyclerView?) {
        recLv!!.adapter = printlnAdapter
        printlnAdapter.setOnItemClickListener(object : PrintBlueAdapter.OnItemClickListener {
            override fun connDevice(device: BluetoothInfoBean) {
                mHandler?.post(Runnable {
                    ZPrinterManager.getsManager(activity).workThread.disconnectBt()

                    // 只有没有连接且没有在用，这个才能改变状态
                    if (ZPrinterManager.getsManager(activity).workThread.connectBt(device)) {
                        printlnAdapter.updateConnStatus(BluetoothInfoBean.CONNECTING, device)
                    }
                })
            }

            override fun onPrint(device: BluetoothInfoBean) {
                if (mLogistics != null){
                    ZPrinterManager.getsManager(activity).workThread.MyPrinter(mLogistics, mUiHandler)
                }
            }

        })
    }

    private val mUiHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 1 && msg.obj != null) {
                val str = msg.obj as String
            }
        }
    }

    /**
     * 开始蓝牙设备搜索
     */
    private fun searchBlutooth() {
        if (mRxPermissions == null){
            mRxPermissions = RxPermissions(this) // where this is an Activity or Fragment instance
        }
        mRxPermissions!!
                .request(Manifest.permission.BLUETOOTH_ADMIN,
                        Manifest.permission.BLUETOOTH,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION)
                .subscribe { granted ->
                    if (granted) {
                        mInfoBeanList.clear()
                        val adapter = BluetoothAdapter.getDefaultAdapter()
                        if (!adapter!!.isEnabled) {
                            adapter!!.enable()
                        }
                        adapter!!.cancelDiscovery()
                        adapter!!.startDiscovery()
                    }
                }
    }

    open fun initBroadcast() {
        broadcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                if (intent != null) {
                    val action = intent.action
                    if (BluetoothDevice.ACTION_FOUND == action) {
                        val device = intent
                                .getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                        if (device != null) {
                            addDevice(device)
                        }
                    } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED == action) {
//                        showLoading()
                    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) {
//                        mLoadingPb.post(Runnable { mLoadingPb.setVisibility(View.GONE) })
                    } else if (action == "BluetoothItem") {
                        val blueTag = intent.getIntExtra("BlueTag", -1)
                        val bean = intent.getSerializableExtra("BluetoothInfo") as BluetoothInfoBean
                        if (blueTag == Global.MSG_INFO_BEAN && bean != null) {
                            updateBTConnected(bean)
                        }
                    } else if (action == "BluetoothStatus") {
                        val sta = intent.getIntExtra("BlueStatus", BT_STA_DISCONNECT)
                    } else if (action == BluetoothDevice.ACTION_ACL_DISCONNECTED) {
                    }
                }
            }
        }
        intentFilter = IntentFilter()
        intentFilter?.addAction(BluetoothDevice.ACTION_FOUND)
        intentFilter?.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
        intentFilter?.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        intentFilter!!.addAction("BluetoothItem")
        intentFilter!!.addAction("BluetoothStatus")
        intentFilter!!.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
        activity?.registerReceiver(broadcastReceiver, intentFilter)
    }

    /**
     * 添加蓝牙列表
     */
    private fun addDevice(device: BluetoothDevice) {
        if (TextUtils.isEmpty(device.name)) {
            refreshLayout.finishRefresh()
            return
        }
        for (d in mInfoBeanList) {
            if (TextUtils.equals(d.address, device.address)) {
                refreshLayout.finishRefresh()
                return
            }
        }

        Log.e("addDevice:", "address:" + device.address)
        val bean = BluetoothInfoBean()
        bean.setAddress(device.address)
        bean.setName(device.name)
        mInfoBeanList.add(bean)
        onGetDataSuc(mInfoBeanList)

        connDefault()
    }

    /**
     * 连接默认设备
     */
    private fun connDefault() {
        val deviceStr = SPUtils.getInstance().getString(Constants.PRINT_DEVICE)
        val device = GsonUtil.parse(deviceStr, BluetoothInfoBean::class.java)
        if (device != null) {
            for (deviceBean in mInfoBeanList) {
                if (TextUtils.equals(deviceBean.address, device.address)) {
                    printlnAdapter.connectDefault(deviceBean)
                }
            }
        }
    }

    /**
     * 更新已连接状态
     */
    private fun updateBTConnected(bean: BluetoothInfoBean) {
        var isConn = BluetoothInfoBean.DISCONNECT
        if (bean.result === 1) {
            if (ZPrinterManager.getsManager(activity).workThread.isConnected) {
                isConn = BluetoothInfoBean.CONNECTED
                SPUtils.getInstance().put(Constants.PRINT_DEVICE, GsonUtil.toJson(bean))
            }
        }
        printlnAdapter.updateConnStatus(isConn, bean)
    }

    private fun uninitBroadcast() {
        if (broadcastReceiver != null) {
            activity?.unregisterReceiver(broadcastReceiver)
        }
    }

    override fun loadData(page: Int, pageCount: Int) {
        searchBlutooth()
    }

    override fun getData(): MutableList<BluetoothInfoBean> {
        return printlnAdapter.data
    }

    override fun bindData(isRefresh: Boolean, list: MutableList<BluetoothInfoBean>?) {
        if (isRefresh) {
            printlnAdapter.setNewData(list)
        } else {
            printlnAdapter.addData(list!!)
        }
    }

    class MHandler : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                Global.MSG_WORKTHREAD_SEND_CONNECTBTRESULT -> {
                    try {
                        val result = msg.arg1
                        val bundle = msg.data ?: return
                        val infoBean = bundle.getSerializable("infoBeans") as BluetoothInfoBean?
                                ?: return
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ZPrinterManager.getsManager(activity).workThread.disconnectBt()
        uninitBroadcast()
        System.gc()
    }
}